/**
 * Created by tanbingqin on 2020/2/27.
 */
import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { message, Tag, Popover, Checkbox, Select } from 'antd'
const { Option } = Select;
import moment from 'moment'
import constants from 'share/constants'
import errorMessage from 'share/errorMessage';
import ExportModal from 'components/template/export-modal/export-modal';
import costApplicationService from 'containers/financial-management/check-cost-application/check-cost-application.service'
import 'styles/financial-management/finance-view.scss'
import CostCenterSearchForm from 'components/template/cost-center-search-form/cost-center-search-form'
import AdvancedTable from 'components/advanced-table'
import selectorData from "share/selectorData"
import openSlideFrame from "share/openSlideFrame";
import DepartmentPicker from "../wait-for-billing/new-billing/department-picker";

class CheckCostApplication extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sort: '',
      searchParams: {}
    }
  }

  statusOptions = [
    { label: messages('request-1.key39')/*审批中*/, value: 'submitted' }, //审批中
    { label: messages('request-1.key40')/*已通过*/, value: 'approval_pass' },  //已通过
    { label: messages('request-1.key367')/*已驳回*/, value: 'approval_reject' }, //已驳回
    { label: messages('request-1.key10')/*已关闭*/, value: 'closed' } //已关闭
  ];

  columns = [
    { title: messages('common.user.id')/*工号*/, dataIndex: 'employeeID' },
    {
      title: messages('common.applicant')/*申请人*/,
      dataIndex: 'applicant',
      render: value => <Popover content={value}>{value}</Popover>
    },
    {
      title: messages('common.submit.date')/*提交日期*/,
      dataIndex: 'lastSubmittedDate',
      render: (date, record) => date ? moment(date).format('YYYY-MM-DD') : moment(record.createDate).format('YYYY-MM-DD'),
      sorter: true
    },
    {
      title: messages('request-1.key790')/*单据类型*/,
      dataIndex: 'formName',
      render: value => <Popover content={value}>{value}</Popover>
    },
    {
      title: messages('common.document.code')/*单号*/,
      dataIndex: 'businessCode',
      sorter: true,
      render: (value, record) => (
        <Popover content={record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}>
          {record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}
        </Popover>
      )
    },
    {
      title: messages('request-1.key172')/*事由*/,
      dataIndex: 'title',
      render: value => {return <Popover placement="topLeft" content={value || '-'}>{value || '-'}</Popover>}
    },
    {
      title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 58,
      render: (value, record) => {
        return record.showAmount ? value : '-'
      }
    },
    {
      title: messages('common.total.amount')/*总金额*/,
      dataIndex: 'totalAmount',
      sorter: true,
      render: (value, record) => {
        return record.showAmount ? this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) : '-'
      }
    },
    {
      title: messages('common.column.status')/*状态*/,
      dataIndex: 'status',
      width: 160,
      render: (value, record) => {
        let applicationType = '';
        (+record.entityType === 1001) && (applicationType = 2005);//申请单下的applicationType是2005
        let text;
        let color;
        if (record.closed || record.participantClosed) {
          text = messages('request-1.key10')/*已关闭*/;
          color = '#d9d9d9';
        } else {
          text = constants.getTextByValue(String(value + '' + applicationType), 'documentStatus') ||
            constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
            constants.getTextByValue(String(value), 'documentStatus');
          color = constants.getTextByValue(String(value + '' + applicationType), 'documentStatus', 'color') ||
            constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
            constants.getTextByValue(String(value), 'documentStatus', 'color');
        };
        return <Tag style={{margin: '0 0'}} color={color}>{text}</Tag>
      }
    },
    {
      title: messages('common.operation')/*操作*/,
      dataIndex: 'operation',
      width: 100,
      render: (value, record) =>
        <a onClick={event => this.print(record, event)}>{messages('common.print')/*打印*/}</a>
    }
  ];

  searchForm = [
    {
      id: 'formOIDs', component: 'MultiSelectorV2', label: messages('request-1.key791')/*表单类型*/,
      props: {
        type: 'authority_form',
        params: { formType: 1001 },
        labelKey: 'formName'
      },
      parser: value => ({
        formOIDs: value ? value.map(item => item.formOID) : null
      })
    },
    {
      id: 'userOID', label: messages('request-1.key792')/*申请人姓名/工号*/, component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('request-1.key792')/*申请人姓名/工号*/,
        selectorItem: {
          ...selectorData['user'],
          url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
            (`（${record.status === 1002 ?
              messages('request-1.key793')/*待离职员工*/ :
              messages('request-1.key794')/*离职员工*/}）`
            ) :
            ''
          )}`)
        }
      }
    },
    { component: 'Input', id: 'businessCode', label: messages('request-1.key795')/*单据ID*/ },
    {
      id: 'dateRange', label: messages('common.submit.date')/*提交日期*/, component: 'DateRangePicker',
      initialValue: [moment().subtract(1, 'month'), moment()],
      parser: value => ({
        beginDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        endDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'approvalDateRange', label: messages('request-1.key796')/*审批日期*/, component: 'DateRangePicker',
      parser: value => ({
        approvalStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        approvalEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'departmentOIDs', label: messages('common.department')/*部门*/,
      component: <DepartmentPicker
        placeholder={messages('common.select')/*请选择*/}
        type='department'
        valueKey="departmentOIDs"
        labelKey="name"
        showNumber
        related
      />,
      parser: value => ({
        departmentOIDs: value ? value.map(item => item.value) : null
      }),
      tagParser: value => messages('common.total.selected',{arg1: value.length})/*已选 {arg1} 条*/,
      JSONObjectFormatterParams: ['value']
    },
    {
      id: 'searchCorporations', label: messages('request-1.key797')/*法人实体*/,
      component: 'Chooser',
      props: {
        type: 'legal_entity',
        labelKey: 'entityName',
        valueKey: 'companyReceiptedOID',
        listKey: 'rows'
      },
      parser: value => ({
        searchCorporations: value ? value.map(item => item.companyReceiptedOID) : null
      }),
      JSONObjectFormatterParams: ['entityName', 'companyReceiptedOID']
    },
    {
      id: 'searchCostCenterCommands', label: messages('request-1.key798')/*成本中心*/,
      component: <CostCenterSearchForm title={messages('request-1.key798')/*成本中心*/}/>,
      tagParser: value => messages('common.total.selected',{arg1: value.length})/*已选 {arg1} 条*/
    },
    {
      id: 'status', label: messages('common.column.status')/*状态*/,
      component: (
        <Checkbox.Group>
          {
            this.statusOptions.map(item => <Checkbox key={item.value} value={item.value}>{item.label}</Checkbox>)
          }
        </Checkbox.Group>
      ),
      tagParser: value => this.statusOptions.filter(item => value.find(key => item.value === key)).map(item => item.label).join(','),
      row: true
    }
  ];

  service = (page, pageSize, searchParams) => {
    const { sort } = this.state;
    let isHasClosed = searchParams.status ? searchParams.status.filter(item => item === 'closed').length > 0 : false; //是否选了已关闭状态
    searchParams.closed = isHasClosed ? 3 : undefined;
    this.setState({searchParams});
    return costApplicationService.getFinanceViewList(page, pageSize, sort, searchParams);
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { sort } = this.state;
    let nextSort = '';
    if(sorter.order) {
      nextSort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
    }
    if(nextSort !== sort) {
      this.setState({ sort: nextSort }, () => {
        this.advancedTableRef.getList(true);
      });
    }
  };

  handleRowClick = (record) => {
    openSlideFrame.openRequestReport({
      formOID: record.formOID,
      applicationOID: record.entityOID,
      entry: 'costApplication',
      readOnly: true
    }, {
      afterClose: value => {
        typeof value === 'boolean' && value && this.advancedTableRef.getList(true);
      }
    }, this);
  };

  render() {
    const { searchParams } = this.state;
    return (
      <div className="full-height-page">
        <AdvancedTable
          service={this.service}
          index
          title={messages('request-1.key799')/*申请单查看*/}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          waterMark
          onChange={this.handleTableChange}
          rowKey='entityOID'
          tableName='check-cost-application'
          columns={this.columns}
          onRef={ref => this.advancedTableRef = ref}
          searchForm={this.searchForm}
          footer={
            <ExportModal
              type={"btn"}
              btnType="primary"
              exportTitle={messages('request-1.key800')/*导出搜索数据*/}
              exportType="FINANCE_APPLICAITON_CHECK"
              exportCondition={{
                billCheckSearchCommand: searchParams
              }}
              exportCommand={'FINANCE_APPLICAITON_CHECK'}
            />
          }
        />
      </div>
    )
  }
}

CheckCostApplication.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user
  }
}

export default connect(mapStateToProps)(CheckCostApplication);
